﻿using System.Collections;
using System.Collections.Generic;
using Editor;
using ProjectTW.Foliage;
using UnityEditor;
using UnityEngine;

public class TestTestEditor : UnityEditor.Editor
{
    private static readonly List<UNCombineInstance> ReusableCombineInstances = new List<UNCombineInstance>();
    
    [MenuItem("Assets/Save Mesh")]
    public static void CreateMesh()
    {
        // Mesh mesh = FoliageMeshManager.CreateNewMesh();
        // mesh.vertices = new Vector3[]
        // {
        //     new Vector3(0, 0, 0), 
        //     new Vector3(0, 0, 1), 
        //     new Vector3(1, 0, 0), 
        // };
        // mesh.triangles = new int[]
        // {
        //     0, 1, 2
        // };
        //
        // mesh.RecalculateNormals();
        //
        // SaveMesh(mesh, "testmesh", true, true);

        var fdb =  FoliageDB.Instance;
        FoliagePrototype prototype = FoliageDB.UnSortedPrototypes[0];

        Mesh mesh = FillMesh(prototype.GetLODsData()[0], prototype, 3, 1);
        MeshEditorUtility.SaveMesh(mesh, "testmesh", true, true);
    }
    
    /// <summary>
    /// Fill a mesh with information.
    /// </summary>
    /// <param name="prototype"></param>
    /// <param name="density"></param>
    /// <param name="units"></param>
    /// <returns></returns>
    private static Mesh FillMesh(FoliageMeshData meshData, FoliagePrototype prototype, int density, int units)
    {
        Mesh mesh = FoliageMeshUtility.CreateNewMesh();
        Vector3 position = new Vector3();
        position.y = prototype.FoliageMesh.Offset.y;

        ReusableCombineInstances.Clear();

        Matrix4x4 matrix;

        Mesh prototypeMesh = prototype.FoliageMesh.Mesh;
        float spread = prototype.Spread;
        int prototypeId = prototype.Id;

        for (int x = 0; x < units; x++)
        {
            for (int z = 0; z < units; z++)
            {
                position.x = x;
                position.z = z;

                matrix = Matrix4x4.TRS(position, Quaternion.identity, Vector3.one);

                for (int densityIndex = 1; densityIndex <= density; densityIndex++)
                {
                    ReusableCombineInstances.Add(new UNCombineInstance(matrix, prototypeMesh, spread, densityIndex, prototypeId, x, z, true));
                }
            }
        }

        FoliageMeshUtility.CombineMeshes(ReusableCombineInstances, mesh, meshData);

        return mesh;
    }
}
